<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

use think\Config;
use think\Session;
use fast\Http;

use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;

class Jdyapp extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

    }

    function getadminnickname($adminid)
    {
        $admin = \app\admin\model\Admin::get($adminid);
        if ($admin) {
            return $admin->nickname;
        }

        return "";
    }

    function getanchanglist($adminuser)
    {
        $anchangidlist = json_decode($adminuser['anchangids'], TRUE);
        $xianshi = [];
        $xianshi[] = $adminuser['xianshi1'];
        $xianshi[] = $adminuser['xianshi2'];
        $xianshi[] = $adminuser['xianshi3'];
        $xianshi[] = $adminuser['xianshi4'];
        $xianshi[] = $adminuser['xianshi5'];

        $xzq = [];
        $xzq[] = $adminuser['xzq1'];
        $xzq[] = $adminuser['xzq2'];
        $xzq[] = $adminuser['xzq3'];
        $xzq[] = $adminuser['xzq4'];
        $xzq[] = $adminuser['xzq5'];

        $xianshis = "";//只有市
        $xianshisA = "";
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xianshi[$i]) && empty($xzq[$i])) {
                if (empty($xianshis)) {
                    $xianshis = $xianshi[$i];
                    $xianshisA = "'" . $xianshis . "'";
                } else if (strpos($xianshis, $xianshi[$i]) === false) {
                    $xianshis .= ',' . $xianshi[$i];
                    $xianshisA .= ",'" . $xianshi[$i] . "'";
                }
            }
        }

        $xzqs = "";//
        $xzqsA = "";//
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xzq[$i]) && !empty($xianshi[$i]) && strpos($xianshis, $xianshi[$i]) === false) {
                if (empty($xzqs)) {
                    $xzqs = $xzq[$i];
                    $xzqsA = "'" . $xzqs . "'";
                } else if (strpos($xzqs, $xzq[$i]) === false) {
                    $xzqs .= ',' . $xzq[$i];
                    $xzqsA .= ",'" . $xzq[$i] . "'";
                }
            }
        }

        $whereA = "";
        if (!empty($xianshis)) {
            $whereA = " xianshi in (" . $xianshisA . ") ";
        }

        if (!empty($xzqs)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " xzq in (" . $xzqsA . ") ";
        }

        $anchangids = "";//"117,116"
        if ($anchangidlist) {
            foreach ($anchangidlist as $row) {
                if (empty($anchangids)) {
                    $anchangids = $row['id'];
                } else {
                    $anchangids .= ',' . $row['id'];
                }
            }
        }

        if (!empty($anchangids)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " id in (" . $anchangids . ") ";
        }

        $list = [];
        if (!empty($whereA)) {
            $list = \app\admin\model\jdy\Anchang::where($whereA)->select();
        }

        return $list;
    }

    function getanchangids($adminuser) {
        $anchangidlist = $this->getanchanglist($adminuser);
        $anchangids = "";
        foreach ($anchangidlist as $row) {
            if (empty($anchangids)) {
                $anchangids = $row['id'];
            } else {
                $anchangids .= ',' . $row['id'];
            }
        }
        return $anchangids;
    }

    function getcontent0($anchang_id, $mode = -1, $keywords="")
    {
        $model = new \app\admin\model\jdy\Maintenance;
        $where0 = "";
        $thismonth = date("Y-m");
        if ($mode == 0) {
            //一个月
            $fromdate = date("Y-m-d H:i:s", strtotime($thismonth));
            $where0 = "create_time > '". $fromdate."'";
        } else if ($mode == 1) {
            //三个月
            $fromdate = date("Y-m-d H:i:s", strtotime("-2 month", strtotime($thismonth)));
            $where0 = "create_time > '". $fromdate."'";
        } else if ($mode == 2) {
            //六个月
            $fromdate = date("Y-m-d H:i:s", strtotime("-5 month", strtotime($thismonth)));
            $where0 = "create_time > '". $fromdate."'";
        }

        if (!empty($keywords)) {
            if (!empty($where0)) {
                $where0 .= " and ";
            }
            $where0 .= "content like '%" . $keywords . "%' ";
        }

        $content0 = "<ul>";
        $list = $model
            ->where('anchang_id', $anchang_id)
            ->where($where0)
            ->field('id, task_id, content, message, switch, create_time, luruman')
            ->order("create_time desc")
            ->select();

        $maintenanceid = 0;
        $taskid = 0;
        foreach ($list as $row) {
            if ($maintenanceid == 0) {
                $maintenanceid = $row['id'];
                $taskid = $row['task_id'];
            }
            $message = "";
            if ($row->message) {
                $message = $row->message;
            }

            $content0 .= "<li>".$row->create_time . "<br>录入人員:" .$row->luruman. "<br>内容:" . $row->content . "<br>主管留言:" . $message . "</li>";
        }

        $content0 .= "</ul>";

//        $this->view->assign("maintenanceid", $maintenanceid);
//        $this->view->assign("taskid", $taskid);

        return $content0;
    }

//http://acciot.test/api/jdyapp/login?account=mirolu&password=123456
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];

            $admin = \app\admin\model\Admin::where("username", $account)->find();
            if (!$admin) {
                $user = $this->auth->getUser();
                $admin = new \app\admin\model\Admin();
                $admin->username = $account;
                $admin->nickname = $account;
                $admin->email = $user->email;
                $admin->phone = $user->mobile;
                $admin->salt = $user->salt;
                $admin->password = $user->password;
                $admin->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $admin->remark = $user->bio;
                $admin->save();

                $aga = new \app\admin\model\AuthGroupAccess();
                $aga->uid = $admin->id;
                $aga->group_id = 11;//未開通帳號
                $aga->save();
            }
            $admin = $admin->toArray();
//            $this->success(__('Logged in successful'), $data);
            $this->success(__('Logged in successful'), $admin);//返回admin
        } else {
            $this->error($this->auth->getError());
        }
    }

    //http://acciot.test/api/jdyapp/register?username=aa&password=123456
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $mobile = $this->request->request('mobile', "");
        $bio = $this->request->request('bio', "");//格言
        $email = $this->request->request('email', $username.'@qq.com');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }

        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];

            $user = $this->auth->getUser();
            if ($user) {
                $admin = new \app\admin\model\Admin();
                $admin->username = $username;
                $admin->nickname = $username;
                $admin->email = $email;
                $admin->phone = $mobile;
                $admin->salt = $user->salt;
                $admin->password = $user->password;
                $admin->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $admin->remark = $bio;
                $admin->save();

                $aga = new \app\admin\model\AuthGroupAccess();
                $aga->uid = $admin->id;
                $aga->group_id = 11;//未開通帳號
                $aga->save();
            }
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //http://acciot.test/api/jdyapp/gettasklistbyadmin?adminid=16&datemode=1
    //获取关联的提醒
    public function gettasklistbyadmin()
    {
        $adminid = $this->request->request('adminid', 0);
        $datemode = $this->request->request('datemode', 0);

        if ($adminid < 1) {
            $this->error(__('Invalid parameters'));
        }
        $adminuser = \app\admin\model\Admin::get($adminid);
        $anchangids = $this->getanchangids($adminuser);

        //<---权限获取
        $isadmin = false;
        $isanchanguser= false;
        $groupIds = [];
        if ($adminuser) {
            $agalist = \app\admin\model\AuthGroupAccess::where('uid', $adminuser->id)->select();
            foreach ($agalist as $row) {
                $groupIds[] = $row->group_id;
            }
        }
        if (in_array("2", $groupIds) || in_array("1", $groupIds)) {
            $isadmin = true;//管理员权限不考虑管辖区域
        }

        if (in_array("5", $groupIds) || in_array("9", $groupIds)) {
            $isanchanguser = true;//案場客戶, 仅关联一个案场
        }
        //--->
        $where1 = "remind_date = '".date("Y-m-d")."'";
        switch ($datemode) {
            default:
                break;
            case 0:
                //今日
                break;
            case 1:
                //最近7天
                $where1 = "remind_date >= '" . date("Y-m-d", strtotime("-7 days", time())) . "' and remind_date <= '" . date("Y-m-d")."'";
                break;
            case 2:
                //最近1個月
                $where1 = "remind_date >= '" . date("Y-m-d", strtotime("-1 month", time())) . "' and remind_date <= '" . date("Y-m-d")."'";
                break;
            case 3:
                //即將到來 -- 未来一周
                $where1 = "remind_date > '" . date("Y-m-d") . "' and remind_date <= '" . date("Y-m-d", strtotime("+7 days", time()))."'";
                break;
        }

        $whereB = "";
        if (!$isadmin) {
            if (empty($anchangids)) {
                $whereB = " anchang_id  = 0 ";
            } else {
                $whereB = " anchang_id in (" . $anchangids . ") ";
            }
        }

        $taskList = (new \app\admin\model\jdy\Task)->with(['anchang'])
            ->where($whereB)
            ->where($where1)
            ->select();
        $taskList = collection($taskList)->toArray();

        $weekarray = array("日", "一", "二", "三", "四", "五", "六");

        foreach ($taskList as &$row) {
            $a = date("w", strtotime($row['remind_date']));
            $row['weekinfo'] =  "星期" . $weekarray[$a];
        }

        $this->success("获取提醒成功", $taskList);
    }

    //http://acciot.test/api/jdyapp/getpaomadeng
    //获取跑马灯
    public function getpaomadeng() {
        $paomadeng = "";
        $marqueelist = \app\admin\model\jdy\Marquee::where("launch", 1)
            ->where("start_date", "<", date("Y-m-d H:i:s"))
            ->where("end_date", ">", date("Y-m-d H:i:s"))
            ->select();

        foreach ($marqueelist as $row0) {
            $paomadeng .= $row0['message'] . "    ";
        }

        if (empty($paomadeng)) {
            $paomadeng = "跑马灯...  ... ";
        }
        $this->success(__('跑马灯'), $paomadeng);
    }

    //http://acciot.test/api/jdyapp/anchanginfo?anchang_id=59
    //获取案场信息
    public function anchanginfo()
    {
        $anchangid = $this->request->request('anchang_id', 0);
        if ($anchangid < 1) {
            $this->error("错误的案场！");
        }
        $anchang = \app\admin\model\jdy\Anchang::get($anchangid)->toArray();
        $this->success("案场信息", $anchang);
    }

    /**
     * 留言歷史
     */
    //http://acciot.test/api/jdyapp/lyls?anchang_id=107
    public function lyls()
    {
        $anchangid = $this->request->request('anchang_id', 0);
        if ($anchangid < 1) {
            $this->error("错误的案场！");
        }
        $msglist = \app\admin\model\jdy\Message::where("anchang_id", $anchangid)->order("id", "desc")->select();

        $msglist = collection($msglist)->toArray();
        foreach ($msglist as &$row) {
            $row['user'] = $this->getadminnickname($row['user_id']);
            $row['hcuser'] = $this->getadminnickname($row['hcuser_id']);
        }

        $this->success("留言歷史", $msglist);
    }

    /**
     * 获取維修紀錄
     */
    //http://acciot.test/api/jdyapp/addmaintenance?anchang_id=146&mode=1&keywords=
    public function getmaintenance()
    {
        $anchangid = $this->request->request('anchang_id', 0);
        if ($anchangid < 1) {
            $this->error("错误的案场！");
        }

        $mode = $this->request->request('mode', 0);
        $anchang = \app\admin\model\jdy\Anchang::get($anchangid)->toArray();

        $keywords = $this->request->request('keywords', "");


        $anchang['content0'] = $this->getcontent0($anchangid, $mode, $keywords);
        $anchang['keywords'] = $keywords;
        $this->success("維修紀錄", $anchang);
    }

    /**
     * 修改維修紀錄
     */
    public function postmaintenance()
    {
        $model = new \app\admin\model\jdy\Maintenance;
        $result = $model->allowField(true)->save($_POST);
        $this->success("修改維修紀錄成功");
    }




}





